package ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.IdRes;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RadioGroup;
import application.App;
import base.BaseBean;
import base.activity.BaseFragmentActivity;
import bean.UpdateBean;
import com.dispatchapp.andlei.R;
import com.maning.updatelibrary.InstallUtils;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.tencent.bugly.crashreport.CrashReport;
import netWork.NetUtils;
import ui.fragment.ErrandsFragment;
import ui.fragment.HomepageFragment;
import ui.fragment.MineFragment;
import utils.APKVersionCodeUtils;
import utils.GsonUtils;
import utils.Logger;
import widget.HiDialog;
import widget.UpdatePopupWindow;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 主界面
 *
 * @author Andlei
 */
public class MainActivity extends BaseFragmentActivity {
    private RadioGroup radioGroup;
    private NetUtils netUtils;
    private HomepageFragment homepageFragment;
    private ErrandsFragment errandsFragment;
    private MineFragment mineFragment;
    private UpdatePopupWindow pop;
    private boolean isFource;
    private boolean isFirstUpdate = true;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(isFirstUpdate){
            Map<String, Object> map = new HashMap<>();
            map.put("app_type", "2");
            map.put("version", APKVersionCodeUtils.getVerName(mActivity));//APKVersionCodeUtils.getVerName(mActivity)
            map.put("device", "1");
            netUtils.get("base/version", map, BaseBean.class, null, false);
        }

        //6.0权限处理
        Acp.getInstance(mActivity).request(new AcpOptions.Builder().setPermissions(
                Manifest.permission.ACCESS_FINE_LOCATION).setPermissions(Manifest.permission.ACCESS_COARSE_LOCATION).build(), new AcpListener() {
            @SuppressLint("MissingPermission")
            @Override
            public void onGranted() {
            }
            @Override
            public void onDenied(List<String> permissions) {
                toast("请开启定位权限，否则无法确认到店！");
            }
        });
    }

    @Override
    protected void findViews() {
        netUtils = new NetUtils(mActivity, netRequestCallBack);
        radioGroup = getView(R.id.rd_group);
        homepageFragment = HomepageFragment.getInstance();
        errandsFragment = ErrandsFragment.getInstance();
        mineFragment = MineFragment.getInstance();
        addFragment(R.id.FrameLayout, homepageFragment);
        addFragment(R.id.FrameLayout, errandsFragment);
        addFragment(R.id.FrameLayout, mineFragment);
        hideAllFragment();
        showFragment(homepageFragment);
    }


    @Override
    protected void formatViews() {
        radioGroup.setOnCheckedChangeListener(mOnCheckedChangeListener);
    }

    RadioGroup.OnCheckedChangeListener mOnCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
            hideAllFragment();
            switch (i) {
                case R.id.rd_menu_homepage:
                    if (homepageFragment == null) {
                        homepageFragment = HomepageFragment.getInstance();
                    }
                    showFragment(homepageFragment);
                    break;
                case R.id.rd_menu_mall:
                    if (errandsFragment == null) {
                        errandsFragment = ErrandsFragment.getInstance();
                    }
                    showFragment(errandsFragment);
                    break;
                case R.id.rd_menu_user:
                    if (mineFragment == null) {
                        mineFragment = MineFragment.getInstance();
                    }
                    showFragment(mineFragment);
                    break;
            }
        }
    };

    @Override
    protected void formatData() {
      // checkInstallApk();
    }

    @Override
    protected void getBundle(Bundle bundle) {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }

    //隐藏所有Fragment
    public void hideAllFragment() {
        hideFragment(mineFragment);
        hideFragment(homepageFragment);
        hideFragment(errandsFragment);
    }

    private NetUtils.NetRequestCallBack netRequestCallBack = new NetUtils.NetRequestCallBack() {
        @Override
        public void success(String action, final BaseBean baseBean, Map tag) {
            switch (action) {
                case "base/version":
                    isFirstUpdate = false;
                    if (baseBean.getCode() == 1) {
                        final UpdateBean bean = (UpdateBean) GsonUtils.getInstance(mActivity).parseComplexJArrayByCommon(baseBean,UpdateBean.class);
                        if (pop == null) {
                            pop = new UpdatePopupWindow(App.getInstance(), bean.update_msg, "1", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    DownloadApp(bean.url.replaceAll("\\\\", ""));
                                }
                            }, new View.OnKeyListener() {
                                @Override
                                public boolean onKey(View view, int i, KeyEvent keyEvent) {
                                    if (i == KeyEvent.KEYCODE_BACK) {
                                        finishActivity();
                                        return true;
                                    }
                                    return false;
                                }
                            });
                        }
                        pop.showAsDropDown(radioGroup);
                    } else if (baseBean.getCode() == 2) {
                        final UpdateBean bean = (UpdateBean) GsonUtils.getInstance(mActivity).parseComplexJArrayByCommon(baseBean,UpdateBean.class);
                        isFource = true;
                        if (pop == null) {
                            pop = new UpdatePopupWindow(App.getInstance(), bean.update_msg, "2", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    DownloadApp(bean.url.replaceAll("\\\\", ""));
                                }
                            }, new View.OnKeyListener() {
                                @Override
                                public boolean onKey(View view, int i, KeyEvent keyEvent) {
                                    if (i == KeyEvent.KEYCODE_BACK) {
                                        finishActivity();
                                        return true;
                                    }
                                    return false;

                                }
                            });
                        }
                        pop.showAsDropDown(radioGroup);
                    }

                    break;
            }
        }

        @Override
        public void error(String action, Throwable e, Map tag) {

        }
    };
    private long clickTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == MotionEvent.BUTTON_BACK) {
            if(!isFource){
                moveTaskToBack(false);
            }

        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isFource) {
                if (SystemClock.uptimeMillis() - clickTime <= 1500) {
                    //如果两次的时间差＜1s，就不执行操作
                    finishActivity();
                } else {
                    //当前系统时间的毫秒值
                    clickTime = SystemClock.uptimeMillis();
                    toast("再按一次退出同学骑士");
                    return false;
                }
            }

        }
        return super.onKeyDown(keyCode, event);
    }


    private void DownloadApp(String url) {
        Logger.d("url--->",url);
        //下载APK
        InstallUtils.with(MainActivity.this)
                //必须-下载地址
                .setApkUrl(url)
                //非必须-下载保存的文件的完整路径+/name.apk，使用自定义路径需要获取读写权限
                //.setApkPath("/data/data/")
                //非必须-下载回调
                .setCallBack(new InstallUtils.DownloadCallBack() {
                    @Override
                    public void onStart() {
                        //下载开始
                        pop.GetProgressBar().setVisibility(View.VISIBLE);
                        pop.GetProgressBar().setProgress(0);
                        pop.Getbtn_shengji().setEnabled(false);
                        pop.Gettv_update_content().setVisibility(View.GONE);
                    }
                    @Override
                    public void onComplete(final String path) {
                        //下载完成
                        pop.GetProgressBar().setVisibility(View.GONE);
                        pop.Gettv_update_content().setVisibility(View.VISIBLE);
                        pop.Getbtn_shengji().setEnabled(true);
                        pop.dismiss();
                        //先判断有没有安装权限---适配8.0
                        //如果不想用封装好的，可以自己去实现8.0适配
                        InstallUtils.checkInstallPermission(mActivity, new InstallUtils.InstallPermissionCallBack() {
                            @Override
                            public void onGranted() {
                                //去安装APK
                                installApk(path);
                            }
                            @Override
                            public void onDenied() {
                                //弹出弹框提醒用户
                                AlertDialog alertDialog = new AlertDialog.Builder(mActivity)
                                        .setTitle("温馨提示")
                                        .setMessage("必须授权才能安装APK，请设置允许安装")
                                        .setNegativeButton("取消", null)
                                        .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                //打开设置页面
                                                InstallUtils.openInstallPermissionSetting(mActivity, new InstallUtils.InstallPermissionCallBack() {
                                                    @Override
                                                    public void onGranted() {
                                                        //去安装APK
                                                        installApk(path);
                                                    }

                                                    @Override
                                                    public void onDenied() {
                                                        //还是不允许咋搞？
                                                        //Toast.makeText(context, "不允许安装咋搞？强制更新就退出应用程序吧！", Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                            }
                                        })
                                        .create();
                                alertDialog.show();
                            }
                        });

                    }
                    @Override
                    public void onLoading(long total, long current) {
                        //下载中
                        pop.GetProgressBar().setProgress(current*100/total);
                    }
                    @Override
                    public void onFail(Exception e) {
                        //下载失败
                        toast("下载失败,请重新下载");
                        pop.GetProgressBar().setVisibility(View.GONE);
                        pop.Gettv_update_content().setVisibility(View.VISIBLE);
                        pop.Getbtn_shengji().setEnabled(true);
                        //pop.dismiss();
                    }
                    @Override
                    public void cancle() {
                        //下载取消
                        toast("下载取消,请重新下载");
                    }
                })
                //开始下载
                .startDownload();
    }

    /**
     * 去安装apk
     */
    private void installApk(String path) {
        InstallUtils.installAPK(mActivity, path, new InstallUtils.InstallCallBack() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFail(Exception e) {

            }
        });
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
    }

    private void checkInstallApk(){
        boolean b ;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            b = getPackageManager().canRequestPackageInstalls();
            if (!b) {
                //没有打开安装权限，弹出提示框询问
                new HiDialog.Builder(this)
                        .setContent("您没有开启安装权限，可能会无法更新安装包，请立即开启")
                        .setLeftBtnText("取消")
                        .setLeftCallBack(new HiDialog.LeftClickCallBack() {
                            @Override
                            public void dialogLeftBtnClick() {

                            }
                        })
                        .setRightBtnText("去开启")
                        .setRightCallBack(new HiDialog.RightClickCallBack() {
                            @Override
                            public void dialogRightBtnClick() {
                                //请求安装未知应用来源的权限
                                //打开设置页面
                                InstallUtils.openInstallPermissionSetting(MainActivity.this, new InstallUtils.InstallPermissionCallBack() {
                                    @Override
                                    public void onGranted() {
                                        //去安装APK
                                    }

                                    @Override
                                    public void onDenied() {
                                        //还是不允许咋搞？
                                        // finish();
                                        //Toast.makeText(context, "不允许安装咋搞？强制更新就退出应用程序吧！", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }).build();

            }
        }
//        InstallUtils.checkInstallPermission(mActivity, new InstallUtils.InstallPermissionCallBack() {
//            @Override
//            public void onGranted() {
//                //去安装APK
//            }
//            @Override
//            public void onDenied() {
//                //没有打开安装权限，弹出提示框询问
//                new HiDialog.Builder(MainActivity.this)
//                        .setContent("您没有开启安装权限，可能会无法更新安装包，请立即开启")
//                        .setLeftBtnText("取消")
//                        .setLeftCallBack(new HiDialog.LeftClickCallBack() {
//                            @Override
//                            public void dialogLeftBtnClick() {
//
//                            }
//                        })
//                        .setRightBtnText("去开启")
//                        .setRightCallBack(new HiDialog.RightClickCallBack() {
//                            @Override
//                            public void dialogRightBtnClick() {
//                                //请求安装未知应用来源的权限
//                                //打开设置页面
//                                InstallUtils.openInstallPermissionSetting(MainActivity.this, new InstallUtils.InstallPermissionCallBack() {
//                                    @Override
//                                    public void onGranted() {
//                                        //去安装APK
//                                    }
//
//                                    @Override
//                                    public void onDenied() {
//                                        //还是不允许咋搞？
//                                        // finish();
//                                        //Toast.makeText(context, "不允许安装咋搞？强制更新就退出应用程序吧！", Toast.LENGTH_SHORT).show();
//                                    }
//                                });
//                            }
//                        }).build();
//            }
//        });
    }
}
